<template>
    <el-select ref="elSelect" popper-class="selectTree" :disabled="disabled" clearable v-model="treeLabel" filterable :filter-method="filterMethod" :placeholder="placeholder" @clear="clearInput">
        <span slot="prefix">
          <slot name="prefix"></slot>
        </span>
      <el-option value="0">
        <el-tree accordion :default-expanded-keys="defaultExpandedKey" :node-key="defaultProps.value" v-loading="loading" @node-click="handleNodeClick"
        :data="options.length ? options : treeData" :props="defaultProps" :filter-node-method="filterNode" highlight-current ref="selectTree"></el-tree>
      </el-option>
    </el-select>
  </template>
  
  <script>
  import { default as fetch } from '@/utils/request'
  export default {
    name: 'selectTree',
    model: {
      prop: 'treeValue',
      event: 'getValue'
    },
    /* 配置项 */
    props: {
      treeValue: String,
      prefixIcon: String,
      placeholder:{
        type: String,
        default:"请选择",
      },
      defaultProps: {
        type: Object,
        default: () => {
          return {
            value: 'code', // ID字段名
            label: 'name', // 显示名称
            children: 'children' // 子级字段名
          }
        }
      },
      request: {
        type: Object,
        default: () => {
          return {}
        }
      },
      treeData: {
        type: Array,
        default: () => {
          return []
        }
      },
      disabled: {
        type: Boolean,
        default: false
      },
      regionCode: String
    },
    data() {
      return {
        filterText: '',
        loading: false,
        options: [],
        treeLabel: '',
        defaultExpandedKey: []
      }
    },
    watch: {
      request: {
        handler(n, o) {
          if (this.options.length) return
          if (JSON.stringify(n) === '{}') return
          this.loading = true
          fetch({
            url: '/' + n.url,
            method: n.method,
            data: {
              ...n.params
            }
          }).then(res => {
            this.loading = false
            Array.isArray(res.body) ? this.options = res.body : this.options.push(res.body)
            if (this.options.length) {
              const filed = this.defaultProps.value
              this.defaultExpandedKey.push(this.options[0][filed])
            }
          })
        },
        deep: true,
        immediate: true
      },
      treeData: {
        handler(n, o) {
          if (n.length) {
            const filed = this.defaultProps.value
            this.defaultExpandedKey.push(n[0][filed])
          }
        },
        immediate: true,
        deep: true
      },
      // 回显选中行政区划的名称
      treeValue: {
        immediate: true,
        handler  (val) {
          this.$nextTick(() => {
            this.$refs['selectTree']?.setCheckedKeys([val])
            this.$refs['selectTree']?.setCurrentKey(val)
            const arr = this.$refs['selectTree']?.getCheckedNodes()
            if (!arr?.length) return
            this.treeLabel = arr.filter(item => item[this.defaultProps.value] === val)[0][this.defaultProps.label]
          })
        }
      },
      regionCode(n, o) {
        let code
        // console.log(n)
        if (n.indexOf('0000') > 0) {
          code = n.substring(0, 2)
          this.$refs.selectTree.filter(code)
          return
        } else if (n.indexOf('00') > 0) {
          code = n.substring(0, 4)
          this.$refs.selectTree.filter(code)
          return
        } else {
          this.$refs.selectTree.filter(n)
        }
      }
    },
    mounted() {
    },
    methods: {
      filterNode(value, data = this.options) {
        if (!value) return true
        if (typeof(value - 0) !== 'string') {
          return data[this.defaultProps.value].indexOf(value) >= 0
        } else {
          return data[this.defaultProps.label].indexOf(value) !== -1
        }/*
        const filed = value - 0 ? 'value' : 'label'
        const val = data[this.defaultProps[filed]].indexOf(value) !== -1 */
      },
      filterMethod(value, data) {
        this.$refs.selectTree.filter(value)
      },
      handleNodeClick(node) {
        const code = node[this.defaultProps.value]
        this.treeLabel = node[this.defaultProps.label]
        this.defaultExpandedKey.push(this.handleCode(node))
        this.$emit('getValue', code, node)
        this.$refs['elSelect'].blur()
      },
      clearInput() {
        this.$emit('getValue', '')
      },
      handleCode(node) {
        const code = node[this.defaultProps.value]
        if (node.level === 1) return code
        if (node.level === 2) {
          return code.substring(0, 2) + '0000'
        } else if (node.level === 3) {
          return code.substring(0, 4) + '00'
        }
      }
    }
  }
  </script>
  <style scoped>
  .selectTree  .el-select-dropdown__item{
    height: 100%;
    min-height: 300px;
    background: #fff;
    padding: 0;
  }
  </style>